package com.geqian.web.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

public class ConversionSerializer extends JsonSerializer<Object> implements ContextualSerializer {


    private SerializationConverter serializerConverter;

    private BeanProperty beanProperty;

    /**
     * 获得字段的类型以及注解，在第一次序列化字段时调用
     *
     * @param serializerProvider
     * @param property
     * @return
     * @throws JsonMappingException
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty property) throws JsonMappingException {
        try {
            this.beanProperty = property;
            Class<? extends SerializationConverter> converter = property.getAnnotation(PropertyConverter.class).serializationConverter();
            if (!converter.isAssignableFrom(DeserializationConverter.class)) {
                serializerConverter = converter.getConstructor().newInstance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 序列化数据
     *
     * @param value
     * @param jsonGenerator
     * @param serializerProvider
     * @throws IOException
     */
    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        try {
            ObjectMapper objectMapper = (ObjectMapper) jsonGenerator.getCodec();
            jsonGenerator.writeObject(serializerConverter.conversion(value, beanProperty, objectMapper));
        } catch (Exception ignored) {
            jsonGenerator.writeObject(value);
        }
    }
}